package org.example.backend.Base.Filter;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.example.backend.Base.Util.JWT;
import org.example.backend.Module.System.User.Pojo.Entity.MyUserDetails;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class JWTFilter extends OncePerRequestFilter {

    private final ObjectMapper objectMapper = new ObjectMapper();

    @Resource
    private RedisTemplate<Object, Object> redisTemplate;

    @Resource
    private JWT jwt;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader("Authorization");

        if(!StringUtils.isBlank(token)) {
            cn.hutool.jwt.JWT parse = jwt.parse(token);

            if(parse != null) {
                long uid = Long.parseLong(parse.getPayload("uid").toString());

                Object object = this.redisTemplate.opsForValue().get("user-token-" + uid);
                if(object != null) {
                    MyUserDetails userDetails = BeanUtil.copyProperties(object, MyUserDetails.class);

                    SecurityContext context = SecurityContextHolder.getContext();
                    context.setAuthentication(new UsernamePasswordAuthenticationToken(userDetails, null, null));
                }
            }
        }

        filterChain.doFilter(request, response);
    }
}
